package com.xhy.documents_collection.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.annotations.OperLog;
import com.xhy.documents_collection.entity.PO.Notice;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.enums.BusinessType;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.service.SysNoticeService;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.utils.R;
import org.aspectj.weaver.ast.Not;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2023-03-20 10:34
 * 通知
 */

@RestController
@RequestMapping("/common/notice")
public class CNoticeController {

    @Resource
    SysNoticeService noticeService;

    @Resource
    UserService userService;

    @GetMapping("/list/{number}")
    public R list(@PathVariable Integer number){

        List<Notice> notices = noticeService.list(new LambdaQueryWrapper<Notice>().orderByDesc(Notice::getGmtCreated));
        if (number == 0 || ObjectUtils.isEmpty(number)){
            return R.ok().data("data",notices);
        }
        notices = notices.stream().limit(number).collect(Collectors.toList());
        return R.ok().data("data",notices);
    }

    @GetMapping("/{id}")
    public R get(@PathVariable Integer id){
        if (ObjectUtils.isEmpty(id)){
            return R.error().message("请选择查看的公告");
        }
        Notice notice = noticeService.getById(id);
        return R.ok().data("data",notice);
    }

    @GetMapping("/newest")
    public R newest(){
        Integer userId = UserHolder.get();
        User user = userService.getById(userId);
        if (user.getNoticeState()){
            return R.ok();
        }
        List<Notice> list = noticeService.list(new LambdaQueryWrapper<Notice>().orderByDesc(Notice::getGmtCreated));
        if (ObjectUtils.isEmpty(list)){
            return R.ok();
        }
        return R.ok().data("data",list.get(0));
    }

    @PostMapping("/receive")
    @OperLog(title = ServiceType.NOTICE,businessType = BusinessType.RECEIVE)
    public R receive(){
        Integer userId = UserHolder.get();
        User user = new User();
        user.setId(userId);
        user.setNoticeState(true);
        userService.updateById(user);
        return R.ok();
    }
}
